package com.concurrence;

import com.Example.Model.Transfer.Transfer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.client.RepChainJksClient;
import com.protos.Peer;
import org.apache.commons.codec.binary.Hex;

import java.util.Random;

public class Node2Thread implements Runnable {

    private RepChainJksClient adminClient = new RepChainJksClient("localhost:8081","jks/12110107bi45jh675g.node2.jks", "123", "12110107bi45jh675g.node2");

    private Peer.ChaincodeId contractAssetsId = Peer.ChaincodeId.newBuilder().setChaincodeName("ContractAssetsTPL").setVersion(1).build();

    // 管理员证书ID
    private Peer.CertId adminCertId = Peer.CertId.newBuilder().setCreditCode("12110107bi45jh675g").setCertName("node2").build();

    private Random random = new Random();

    private int node2;

    private int node3;

    private int[] amount = new int[]{0,0,0,0,0,0};

    @Override
    public void run() {
        try {
            for (int i = 1; i <= 1000; i++) {
//                int amount = random.nextInt(100);
                int amount = 50;
                Transfer.TransferBuilder builder = Transfer.builder();
                builder.from("12110107bi45jh675g");
                builder.to("122000002n00123567");
                builder.amount(amount);
                node2 -= amount;
                node3 += amount;
                String str_trans = JSON.toJSONString(builder.build());
                //这个是给转账交易示范用的，此ID需要与repchain合约部署的一致
                Peer.Transaction transfer = adminClient.createTransactionForInvoke(adminCertId, contractAssetsId, "transfer", str_trans);
                String transferstr = Hex.encodeHexString(transfer.toByteArray());
                // 将交易数据post过去
                JSONObject transferResult = adminClient.postTranByString(JSONObject.toJSONString(transferstr));
                System.out.println(Thread.currentThread().getName() + ": " + transferResult);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public int getNode2() {
        return node2;
    }

    public void setNode2(int node2) {
        this.node2 = node2;
    }

    public int getNode3() {
        return node3;
    }

    public void setNode3(int node3) {
        this.node3 = node3;
    }
}
